package com.scedu.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.scedu.config.JWTConfig;
import com.scedu.domain.SysUser;
import com.scedu.entity.Payload;
import com.scedu.utils.JwtUtil;
import com.scedu.utils.ResponseJson;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationConverter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class JwtVerifyFilter extends BasicAuthenticationFilter {

    private JWTConfig jwtConfig;

    public JwtVerifyFilter(AuthenticationManager authenticationManager,JWTConfig jwtConfig) {
        super(authenticationManager);
        this.jwtConfig=jwtConfig;
    }

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            //请求体的头中是否包含Authorization
            String header = request.getHeader("Authorization");
            //Authorization中是否包含Bearer，不包含直接返回未登录提示
            if (header == null || !header.startsWith("Bearer ")) {
                chain.doFilter(request, response);
                ResponseJson.response(response,HttpServletResponse.SC_FORBIDDEN,"请登录！"); //返回未登录提示
                return;
            }
            //通过token，获取用户信息
            UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
            //获取后，将Authentication写入SecurityContextHolder中供后序使用
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } catch (Exception e) {
            ResponseJson.response(response,HttpServletResponse.SC_FORBIDDEN,"请登录！"); //返回未登录提示
            e.printStackTrace();
        }


    }

    /**
     * 通过token，获取用户信息
     *
     * @param request
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null) {
        //通过token解析出载荷信息
            Payload<SysUser> payload = JwtUtil.getInfoFromToken(token.replace("Bearer ", ""),
                    jwtConfig.getSecretKey(), SysUser.class);
            SysUser user = payload.getUserInfo();
        //不为null，返回
            if (user != null) {
                return new UsernamePasswordAuthenticationToken(user, null, user.getRoles());
            }
            return null;
        }
        return null;
    }

}
